<?php

namespace App\Http\Controllers\Api\Patient;

use App\Http\Controllers\ApiController;
use App\Models\Hospital;
use App\Models\Patient;
use App\Models\UserBase;
use App\Transformers\Api\MedicalRecordTransformer;
use App\Transformers\Api\PatientTransformer;
use App\LogicService\Contracts\HospitalManageLogicContract;
use App\LogicService\Contracts\HospitalLogicContract;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
use Illuminate\Http\Request;

class PatientController extends ApiController
{
    /**
     * @var \Illuminate\Http\Request
     */
    protected $request;

    protected $hospitalManage;

    protected $hospitalLogicContract;


    public function __construct(Request $request, HospitalManageLogicContract $hospitalManage, HospitalLogicContract $hospitalLogicContract)
    {
        parent::__construct();
        $this->hospitalManage = $hospitalManage;
        $this->hospitalLogicContract = $hospitalLogicContract;
        $this->request = $request;
    }

    public function info()
    {
        return $this->item(
            $this->getThePatient(),
            (new PatientTransformer())->setDefaultIncludes(['physique'])
        );
    }

    public function recordList()
    {
        $record = $this->getThePatient()->records();

        return $this->collection($record, new MedicalRecordTransformer());
    }

    /**
     * @return \App\Models\Patient
     */
    protected function getThePatient()
    {
        $user = \Auth::user();

        if ($user instanceof Patient) {
            $patient = $user;
        } else {
            $this->validate($this->request, ['patient_id' => 'required|integer|min:1']);

            $patient = Patient::simpleField()->findOrFail($this->request->input('patient_id'));
        }

        return $patient;
    }


    public function patientList()
    {
        $this->validate($this->request, [
            'page' => 'numeric',
            'ps' => 'numeric',
            'name' => 'sometimes|required|string',
            'hospital_id' => 'sometimes|required|numeric',
            'doctor_id' => 'sometimes|required|numeric',
        ]);
        $user = \Auth::user();
        $hospital_ids = $this->hospitalId($user);
        $ps = $this->request->input('ps', 10);
        $page = $this->request->input('page', 1);
        $name = $this->request->input('name');
        $hospital_id = $this->request->input('hospital_id');
        $doctor_id = $this->request->input('doctor_id');

        $wheres[] = ['tn_user_base.type', '=', '1'];
        $wheres[] = ['st_medical_records.is_del', '=', '0'];
        if ($name) {
            $wheres[] = ['tn_user_base.name', 'like', '%' . $name . '%'];
        }
        if ($hospital_id) {
            $wheres[] = ['st_medical_records.hospital_id', '=', $hospital_id];
        }
        if ($doctor_id) {
            $wheres[] = ['st_medical_records.doctor_id', '=', $doctor_id];
        }
        $users = UserBase::select(['tn_user_base.id', 'tn_user_base.name', 'tn_user_base.phone', 'tn_user_base.created_at', 'tn_user_base.account'])
            ->join('st_medical_records', 'tn_user_base.id', 'st_medical_records.patient_id')
            ->where($wheres)->whereIn('st_medical_records.hospital_id', $hospital_ids)->distinct()->orderBy('tn_user_base.created_at', 'desc')
            ->skip(($page - 1) * $ps)->take($ps)->get();
        $count = UserBase::select(['tn_user_base.id', 'tn_user_base.name', 'tn_user_base.phone', 'tn_user_base.created_at', 'tn_user_base.account'])
            ->join('st_medical_records', 'tn_user_base.id', 'st_medical_records.patient_id')
            ->where($wheres)->whereIn('st_medical_records.hospital_id', $hospital_ids)->distinct()->orderBy('tn_user_base.created_at', 'desc')->count('tn_user_base.id');

        $users =  new LengthAwarePaginator($users, $count, $ps, $page, [
            'path' => Paginator::resolveCurrentPath(),
            'pageName' => 'page',
        ]);

        foreach ($users as $key => &$value) {
            $value->pic = $this->getPic($value);
            $value->DIABETESTYPE = 0;
            if ($value->patient) {
                $value->DIABETESTYPE = $value->patient->DIABETESTYPE;
            }
            unset($value->detail);
            unset($value->patient);
        }

        return $this->response($users->toArray());


    }


    public function hospitalList()
    {

        $user = \Auth::user();
        $hospital_ids = $this->hospitalId($user);

        $hospitals = $this->hospitalLogicContract->getHospitalsByIds($hospital_ids);
        $hospitals = $hospitals->toArray();

        if ($user->type == 0 || $user->type == 4) {
            array_unshift($hospitals, ['name' => '全部', 'id' => null]);
        }

        return $this->response($hospitals);

    }

    public function doctorList()
    {
        $this->validate($this->request, [
            'hospital_id' => 'sometimes|required|numeric',
        ]);

        $user = \Auth::user();
        $hospital_ids = $this->hospitalId($user);

        $wheres[] = ['type', '=', '2'];
        if ($user->type == 2) {
            $users[] = ['name' => $user->name, 'id' => $user->id, 'phone' => $user->phone];
            return $this->response($users);
        }
        $hospital_id = $this->request->input('hospital_id');
        if ($hospital_id) {
            $wheres[] = ['hospital_id', '=', $hospital_id];
        }
        $users = UserBase::select(['id', 'name', 'phone'])->where($wheres)->whereIn('hospital_id', $hospital_ids)->orderBy('created_at', 'desc')->get()->toArray();

        if ($user->type == 0 || $user->type == 4 || $user->type == 3) {
            array_unshift($users, ['name' => '全部', 'id' => null, 'phone' => null]);
        }

        return $this->response($users);

    }

    public function hospitalId($user)
    {
        $type = $user->type;
        $hospital_ids = array();

        switch ($type) {
            case 0:
                $hospitals = Hospital::get();
                foreach ($hospitals as $key => $value) {
                    $hospital_ids[] = $value->id;
                }
                break;
            case 2:
                $hospitalManage = $this->hospitalManage->show($user->account);// 账号 -> 管理医院
                $hospital_ids = json_decode($hospitalManage->hospital_ids);
                $hospital_ids[] = $user->hospital_id;
                break;
            case 3:
                $hospitalManage = $this->hospitalManage->show($user->account);// 账号 -> 管理医院
                $hospital_ids = json_decode($hospitalManage->hospital_ids);
                $hospital_ids[] = $user->hospital_id;
                break;

        }

        return $hospital_ids;
    }


    public function getPic(UserBase $user)
    {


        if ($user->type == 1) {
            $pic = 'http://www.365tang.cn/upload/face/user_man.png';
            if ($user->patient) {
                if ($user->patient->PIC) {
                    if (!Str::startsWith($user->patient->PIC, 'http')) {
                        $pic = 'http://www.365tang.cn/upload/face/' . $user->patient->PIC;
                    } else {
                        $pic = $user->patient->PIC;
                    }
                }
            }

        } else {

            if ($user->sex == 1) {
                $pic = 'http://www.365tang.cn/upload/public/doctor_female.png';
            } else {
                $pic = 'http://www.365tang.cn/upload/public/doctor_male.png';
            }

            if ($user->detail) {
                if ($user->detail->PIC) {
                    if (!Str::startsWith($user->detail->PIC, 'http')) {
                        $pic = 'http://www.365tang.cn/upload/' . $user->detail->PIC;
                    } else {
                        $pic = $user->detail->PIC;
                    }

                }
            }

        }
        return $pic;
    }
}
